﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Dashboard
{
    public partial class UsersAccessLog : PRO_DOCS.BLL.WIN.Templates.DevxPermissionUserControlTemplate
    {
        private IBindingList _source;
        public UsersAccessLog()
        {
            InitializeComponent();

        }
        #region EXPORT CHART

        private void tsbExportImg_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Jpeg file | *.jpeg";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                chartControl1.ExportToImage(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

        }

        private void tsbExportPDF_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Pdf file | *.pdf";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                DevExpress.XtraPrinting.PdfExportOptions PdfExportOptions = new DevExpress.XtraPrinting.PdfExportOptions();
                PdfExportOptions.Compressed = false;
                PdfExportOptions.ConvertImagesToJpeg = true;
                PdfExportOptions.DocumentOptions.Author = "ECHO";
                PdfExportOptions.DocumentOptions.Subject = "Real time user access log report";
                PdfExportOptions.ImageQuality = DevExpress.XtraPrinting.PdfJpegImageQuality.Highest;
                chartControl1.ExportToPdf(sfd.FileName, PdfExportOptions);
            }
        }

        private void tsbExportXLSX_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Excel file | *.xlsx";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                DevExpress.XtraPrinting.XlsxExportOptions xlsxExportOptions = new DevExpress.XtraPrinting.XlsxExportOptions();
                xlsxExportOptions.ShowGridLines = true;
                
                xlsxExportOptions.ExportMode = DevExpress.XtraPrinting.XlsxExportMode.SingleFile;
                xlsxExportOptions.SheetName = "UAL " + DateTime.Now.ToString("dd.MM.yyyy");
                xlsxExportOptions.ExportHyperlinks = true;
                xlsxExportOptions.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Value;
                chartControl1.ExportToXlsx(sfd.FileName, xlsxExportOptions);
            }
        }

        private void tsbExportRTF_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "RFT file | *.rtf";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                chartControl1.ExportToRtf(sfd.FileName);
            }
        }
        #endregion
        private delegate List<UsersState> FlusherGetUsersState();
        private void LoadUsersState(IAsyncResult result)
        {
            var flusher = (FlusherGetUsersState)result.AsyncState;
            var res = flusher.EndInvoke(result);
            imageListBoxControl1.BeginInvoke(new Action(delegate
                                                            {
                                                                imageListBoxControl1.ValueMember = "ID";
                                                                imageListBoxControl1.DisplayMember = "Name";
                                                                imageListBoxControl1.ImageIndexMember = "IsNowOnline";
                                                                imageListBoxControl1.DataSource = res;
                                                            }));
        }

        private List<UsersState> GetUsersState()
        {
            try
            {
                var list = PRO_DOCSDatabaseDataContext.proc_GET_ALL_USERS_ONLINE_STATUS().ToList();
                return list.Select(m => new UsersState
                                            {
                                                ID = m.AUTOMATIC_ID,
                                                Name = m.EMPLOYEE_FULL_NAME,
                                                IsNowOnline = ((m.STATUS.ToLower() == "online") ? 1 : 0)
                                            }).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void intervalCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            if (intervalCheckEdit.Checked)
            {
                intervalGroupControl.Enabled = true;
            }
            else
            {
                intervalGroupControl.Enabled = false;
            }
        }

        private void UsersActivity_Load(object sender, EventArgs e)
        {
            var flusher = new FlusherGetUsersState(GetUsersState);
            flusher.BeginInvoke(LoadUsersState, flusher);

            _source = new BindingList<KeyValuePair<string, int>>();
            chartControl1.DataSource = _source;
            chartControl1.Series[0].ArgumentDataMember = "Key";
            chartControl1.Series[0].ValueDataMembers.AddRange("Value");

        }

        private void allCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            if (allCheckEdit.Checked)
                imageListBoxControl1.SelectAll();
            else
                imageListBoxControl1.SelectedIndex = -1;
        }

        private void reloadButton_Click(object sender, EventArgs e)
        {
            _source.Clear();
            dxErrorProvider1.ClearErrors();
            var from = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            var to = DateTime.Now;

            var emps = (from UsersState itm in imageListBoxControl1.SelectedItems
                        select itm).ToList();

            if (todayCheckEdit.Checked)
            {
                var flusher = new LoadUserLognPeriod(LoadData);
                flusher.BeginInvoke(-1, from, to, emps, null, flusher);
            }
            else
            {
                if (fromDateEdit.DateTime != new DateTime() && toDateEdit.DateTime != new DateTime())
                {
                    from = fromDateEdit.DateTime;
                    to = toDateEdit.DateTime;

                    var flusher = new LoadUserLognPeriod(LoadData);
                    flusher.BeginInvoke(-1, from, to, emps, null, flusher);
                }
                else
                {
                    dxErrorProvider1.SetError(fromDateEdit, "Enter a valida data");
                    dxErrorProvider1.SetError(toDateEdit, "Enter a valida data");
                }
            }
        }

        private delegate void LoadUserLognPeriod(long? _cURRENT_SELECTED_USER_ID, DateTime _fROM_DATE, DateTime _tO_DATE, IEnumerable<UsersState> _uSERS_STATUSES);
        private void LoadData(long? _cURRENT_SELECTED_USER_ID, DateTime _fROM_DATE, DateTime _tO_DATE, IEnumerable<UsersState> _uSERS_STATUSES)
        {
            var res =
                PRO_DOCSDatabaseDataContext.proc_GET_ALL_USERS_ACCESS_HISTORY(_fROM_DATE, _tO_DATE, int.Parse(_cURRENT_SELECTED_USER_ID.Value.ToString())).ToList();

            List<KeyValuePair<string, int>> rows;

            if (_uSERS_STATUSES.Any())
                rows =
                    res.Where(m => _uSERS_STATUSES.Select(s => s.Name).Contains(m.EMPLOYEE_FULL_NAME)).GroupBy(m => m.EMPLOYEE_FULL_NAME).Select(
                        m => new KeyValuePair<string, int>(m.Key, m.Count())).ToList();
            else
                rows =
                    res.GroupBy(m => m.EMPLOYEE_FULL_NAME).Select(
                        m => new KeyValuePair<string, int>(m.Key, m.Count())).ToList();

            foreach (var pair in rows)
                _source.Add(pair);

        }
    }

    public class UsersState
    {
        public long? ID { get; set; }

        public int IsNowOnline { get; set; }

        public string Name { get; set; }
    }
}
